import { t } from '@/i18n';
import { getCookie } from '@/utils/utils';
import Axios from 'axios'
import { ElMessage } from 'element-plus';

const fileRequest = Axios.create()
fileRequest.defaults.baseURL = '/api-service'

fileRequest.interceptors.request.use(config => {
    const token = getCookie('SaaS_Token');
    config.headers.Authorization = token;
    return config
})

export interface APIResponse<T = unknown> {
    code: number,
    message?: string,
    result?: T
}

/**
 * 上传图片
 * @param file 
 * @returns 
 */
export function uploadImage(file: File) {
    // 格式处理
    const supportImageMineType = ['image/png', 'image/jpeg']
    if (!supportImageMineType.includes(file.type)) {
        ElMessage.error(t('responseMsg.unknownError'));
        return Promise.reject(new Error('文件格式错误，仅支持 PNG 与 JPG 格式图片'))
    }

    const formData = new FormData()
    formData.append('file', file)
    return fileRequest.post<APIResponse<string>>('/saas-public/housekeeper/image/upload', formData).then(res => {
        if (res.data.code !== 200 || res.data.result === '上传失败') {
            ElMessage.error(t('responseMsg.unknownError'));
            throw new Error('图片上传失败')
        }
        return res
    })
}

export function getImage(name: string) {
    return fileRequest.get<Blob>('/saas-public/housekeeper/image', {
        params: { name: name },
        responseType: 'blob'
    })
}